﻿using Jizsoft.JFrame.Result;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jizsoft.JFrame.Modeling.Domain.Services
{
    public class DeleteService
    {
        public ServiceResult DeleteModelField(Guid id)
        {
            using (JFDbContext dbContext = new JFDbContext())
            {
                Entities.ModelField field = dbContext.Set<Entities.ModelField>().SingleOrDefault(p => p.Id == id);

                if (field != null)
                {
                    dbContext.Entry<Entities.ModelField>(field).State = System.Data.Entity.EntityState.Deleted;
                    try
                    {
                        dbContext.SaveChanges();
                        return new Result.ServiceResult();
                    }
                    catch (Exception ex)
                    {
                        return new Result.ServiceResult(1, ex.Message);
                    }
                }

                return new Result.ServiceResult();
            }
        }

        /// <summary>
        /// model1关联了model2
        /// </summary>
        /// <param name="model1Id"></param>
        /// <param name="model2Id"></param>
        /// <returns></returns>
        public ServiceResult DeleteModelRelation(Guid model1Id, Guid model2Id)
        {
            Entities.ModelRelation relation = new Entities.ModelRelation()
            {
                Model1Id = model1Id,
                Model2Id = model2Id
            };

            using (JFDbContext dbContext = new JFDbContext())
            {
                try
                {
                    dbContext.Set<Entities.ModelRelation>().Attach(relation);
                    dbContext.Set<Entities.ModelRelation>().Remove(relation);
                    dbContext.SaveChanges();
                    return new Result.ServiceResult();
                }
                catch (Exception ex)
                {
                    return new Result.ServiceResult(1, ex.Message);
                }
            }
        }
    }
}
